<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Service;

use App\Database\Mysql\Demo;
use Grpc\Base\Common\V1\CreateUserRequest;
use Grpc\Base\Common\V1\CreateUserResponse;
use Hyperf\Grpc\StatusCode;
use Hyperf\GrpcServer\Exception\GrpcException;
use Hyperfx\Framework\Logger\Logx;

class CreateUserService extends BaseService
{
    public function checkRequest(CreateUserRequest $request): void
    {
        if (empty($request->getUsername())) {
            throw new GrpcException('username is empty', StatusCode::INVALID_ARGUMENT);
        }
        if (empty($request->getPassword())) {
            throw new GrpcException('password is empty', StatusCode::INVALID_ARGUMENT);
        }
        if (empty($request->getName())) {
            throw new GrpcException('name is empty',StatusCode::INVALID_ARGUMENT);
        }
    }

    public function handle(CreateUserRequest $request): CreateUserResponse
    {
        $model = new Demo();
        $model->username = $request->getUsername();
        $model->password = $request->getPassword();
        $model->name = $request->getName();

        try {
            $model->save();
        } catch (\Throwable $e) {
            Logx::get()->alert(sprintf('[db] query[%s]failed, error: %s', $model->getTable(), $e->getMessage()));
            throw new GrpcException('create user failed', StatusCode::INTERNAL);
        }

        $response = new CreateUserResponse();
        $response->setId($model->id);
        return $response;
    }
}
